use std::sync::Arc;

use axum::extract::{Path, State};
use axum::http::{HeaderMap, StatusCode};
use axum::{Json, Router};
use axum::routing::get;
use futures::future::ok;
use serde_json::Value;
use tokio::sync::Mutex;
use tracing::info;

use crate::app_state::AppState;
use crate::controller::point_controller::get_machine_index;
use crate::util_entity::anyhow_res::{json_success_response, JsonResult};
use crate::util_entity::response::{json_failed, json_success};

pub fn route() -> Router<Arc<Mutex<AppState>>> {
    Router::new()
        .route("/GetTree", get(get_tree))
        .route("/GetSystemById/:id", get(get_system_by_id))
}
pub async fn get_tree(
    State(app_state): State<Arc<Mutex<AppState>>>,
    headers: HeaderMap,
) -> JsonResult<Value> {
    let machine_index = get_machine_index(headers);

    info!("machine_index : {}, ", machine_index);
    let points = app_state.lock().await.system_repo.get_tree(machine_index).await?;
    Ok(json_success_response(points))
}

pub async fn get_system_by_id(
    State(app_state): State<Arc<Mutex<AppState>>>,
    headers: HeaderMap,
    Path(id): Path<i32>,
) -> JsonResult<Value> {
    let machine_index = get_machine_index(headers);

    info!("machine_index : {}, ", machine_index);
    let points = app_state.lock().await.system_repo.get_by_id(machine_index, id).await?;
    Ok(json_success_response(points))
}